import Taro, { Component, Config } from '@tarojs/taro'
import { Button, View } from '@tarojs/components'
import './index.scss'
import { ORDER_TYPE, ORDER_TYPE_NAME } from "@/config/types"
import { getOrderInfo, refundOrder, confirmReceipt } from "@/api/orderApi"
import { formatTime, getSubscribeMessage} from "@/utils/utils"
import { Loading, OrderRefundModal } from "@/components/index"
import OrderCardGoods from "@/components/order/cart-goods"
import { toHomePage, toOrderCommentPage } from "@/utils/page_router"

export default class Index extends Component {
  state: any
  timer: any
  seconds: number

  config: Config = {
    navigationBarTitleText: '订单详情'
  }

  constructor() {
    super(...arguments)
    const { params } = this.$router
    this.state = {
      id: params.id,
      loading: true,
      cartList: [],
      userInfo: {},
      orderInfo: {},
      isOpened: false
    }
  }

  componentDidShow() {
    setTimeout(() => {
      this.getOrderInfo()
    }, 2000)
  }


  /**
   * 开启倒计时
   */
  setTimer(seconds) {
    this.seconds = seconds
    if (!this.timer) this.countdown()
  }

  /**
   * 清除计时器
   */
  clearTimer() {
    if (this.timer) {
      clearTimeout(this.timer as number)
      this.timer = undefined
    }
  }

  /**
   * 倒计时
   */
  countdown() {
    if (this.seconds === undefined) {
      return;
    }

    this.timer = setInterval(() => {
      this.seconds--

      getOrderInfo(this.state.id).then(({ data }) => {
        this.setState({
          orderInfo: data
        })
      })

      if (this.seconds <= 0) {
        this.clearTimer()
      }
    }, 1000)
  }

  //  订单详情
  getOrderInfo() {
    getOrderInfo(this.state.id).then(({ data }) => {
      this.setState({
        cartList: data.cartSnap,
        userInfo: data.addressSnap,
        orderInfo: data,
        storeInfo: data.cooperateShopAddressSnap,
        loadingStatus: false
      }, () => {
        this.setTimer(10)
        this.setState({
          loading: false
        })
      })
    })
  }

  //  确认退单
  onConfirmRefund(content) {
    const { id, orderInfo } = this.state
    //  订阅通知模板
    Taro.requestSubscribeMessage({
      tmplIds: getSubscribeMessage('orderRefund'),
      complete: () => {
        Taro.showLoading({ title: '请稍后', mask: true })
        refundOrder({ id, content }).then(() => {
          this.setState({
            isOpened: false,
            orderInfo: { ...orderInfo, refundAble: 0 }
          }, () => {
            Taro.hideLoading()
            Taro.showToast({ title: '提交成功' })
          })
        })
      }
    })
  }

  //  订单确认收货
  orderConfirmReceipt() {
    const { orderInfo } = this.state
    Taro.showLoading({ title: '请稍后', mask: true })
    confirmReceipt(this.state.id).then(() => {
      Taro.showToast({ title: '确认成功' })
      this.getOrderInfo()
      Taro.showModal({
        title: '提示',
        content: '是否前往评论',
        success ({ confirm }) {
          confirm && toOrderCommentPage(orderInfo.id)
        }
      })
    })
  }

  render() {
    const { loading, cartList, userInfo, storeInfo, orderInfo, isOpened } = this.state
    return (<View className='detail-page order-info'>
      {loading && <Loading isCover/>}
      <View className='order-card detail-header d-f f-d-c p-0'>
        {
          orderInfo.distribute === 1 ? (
            <View className='order-card__body user-info d-f f-d-c f-w-w'>
              <View className='user-box d-f a-i-c j-c-b'>
                <View className='user-name t-o-e'>{storeInfo.shopName}</View>
                <View className='user-phone t-o-e'>{storeInfo.phone}</View>
              </View>
              <View className='user-box user-address'>{storeInfo.address}</View>
            </View>
          ) : (
            <View className='order-card__body user-info d-f f-d-c f-w-w'>
              <View className='user-box d-f a-i-c j-c-b'>
                <View className='user-name t-o-e'>{userInfo.name}</View>
                <View className='user-phone t-o-e'>{userInfo.telephone}</View>
              </View>
              <View className='user-box user-address'>{userInfo.city} {userInfo.detail}</View>
            </View>
          )
        }
      </View>

      <View className='order-card order-card__body'>
        <View className='cart-list'>
          {cartList.map(cart => {
            return (<OrderCardGoods key={cart.id} info={cart} isJump className='cart-item thin-border__b'/>)
          })}
        </View>
        {/*{!!orderInfo.refundAble && <View className='refund-box d-f a-i-c j-c-e'>*/}
        {/*  <Button className='refund-btn xf-btn xf-btn-round' hoverClass='hover-class--btn' onClick={this.setState.bind(this, { isOpened: true })}>退单</Button>*/}
        {/*</View>}*/}
        <View className='detail-list'>
          {orderInfo.discountAmount && <View className='detail-item'>
            <View className='item-left'>优惠金额：</View>
            <View className='item-right bnn-number'>￥{orderInfo.discountAmount}</View>
          </View>}
          {orderInfo.freightAmount && <View className='detail-item'>
            <View className='item-left'>运费</View>
            <View className='item-right bnn-number'>￥{orderInfo.freightAmount}</View>
          </View>}
          <View className='detail-item'>
            <View className='item-left'>共{cartList.length}件商品</View>
            <View className='item-right pay-amount bnn-number'>￥{orderInfo.payAmount}</View>
          </View>
          <View className='detail-item'>
            <View className='item-left'>订单备注：</View>
            <View className='item-right'>{orderInfo.remark || '无'}</View>
          </View>
        </View>
      </View>

      <View className='order-card'>
        <View className='order-card__head'>订单信息</View>
        <View className='order-card__body'>
          <View className='detail-list'>
            <View className='detail-item'>
              <View className='item-left'>订单状态：</View>
              <View className='item-right order-status'>{ORDER_TYPE_NAME[orderInfo.status]}</View>
            </View>
            <View className='detail-item'>
              <View className='item-left'>订单编号：</View>
              <View className='item-right'>{orderInfo.id}</View>
            </View>
            <View className='detail-item'>
              <View className='item-left'>订单时间：</View>
              <View className='item-right'>{formatTime(orderInfo.createdAt)}</View>
            </View>
          </View>
        </View>
      </View>

      <View className='float-box--height'/>
      <View className='fy-popup fy-popup--bottom float-box d-f a-i-c j-c-b'>
        <Button className='confirm-btn xf-btn xf-btn-round xf-btn-primary' onClick={() => toHomePage()}>返回首页</Button>
        {ORDER_TYPE.SENDING === orderInfo.status && <Button className='confirm-btn xf-btn xf-btn-round xf-btn-primary' onClick={this.orderConfirmReceipt.bind(this)}>确认收货</Button>}
      </View>

      <OrderRefundModal
        isOpened={isOpened}
        onClose={this.setState.bind(this, { isOpened: false })}
        onConfirm={this.onConfirmRefund.bind(this)}/>
    </View>)
  }
}
